/*
 * @Description: 中间层入口(中间件)
 * @Autor: HuiSir<273250950@qq.com>
 * @Date: 2020-11-08 23:25:42
 * @LastEditTime: 2020-11-11 18:27:33
 */

const Koa = require('koa')
const bodyparser = require('koa-bodyparser')
const cors = require('koa2-cors') //解决跨域中间件
const app = new Koa()
const isDev = process.argv.includes('--dev') //开发环境
const router = require('./src/api') //路由
const { RES } = require('./config') //配置
const { Log, Print } = require('./src/utils/logger') //日志

//中间件
app.use(bodyparser())

//允许跨域
if (isDev) {
    app.use(cors())
    //打印日志
    Print.info('已配置跨域')
}

//错误捕获
app.use(async (ctx, next) => {
    try {
        await next()
    } catch (err) {
        //前台捕获
        const status = err.statusCode || err.status || 500
        ctx.response.status = status
        ctx.response.type = 'json'
        ctx.response.body = RES.fail(err.message) //返回错误
        //后台捕获
        const statusWhiteList = [401, 403, 404, 200]
        if (!statusWhiteList.includes(status)) ctx.app.emit('error', err, ctx) //如果错误被try...catch捕获，就不会触发error事件，故需要使用emit方法
    }
})

//启动路由
app.use(router.routes())

//打印日志
Print.info('路由启动成功')

//后台错误捕获
app.on('error', (err) => {
    Log.error(err.message)
})

module.exports = app
